package com.algernoon.nettydemo.netty.server;

import java.nio.charset.Charset;
import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class TimeServerHandler extends ChannelHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// ByteBuf类似于JDK的ByteBuffer
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()]; // readableBytes获取到缓存区的可读字节数
		buf.readBytes(req); // 将缓存区的字节数组复制到新建的byte数组中
		String body = new String(req, Charset.forName("UTF-8"));
		System.out.println("request body is " + body);
		String currentTime = "QUERY_TIME_ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString()
				: "BAD ORDER PARAMETER";
		ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.write(resp); // 异步发送应到消息给客户端
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// 将消息发送队列中的消息写入到SocketChannel中发送给对方
		// 从性能角度考虑，Netty的write方法不直接将消息写入SocketChannel中，调用write方法只是把带发送的消息放入发送缓存数组中，再
		// 通过调用flush方法，将发送缓存区的消息全部发送到SocketChannel中
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) throws Exception {
		// 关闭ChannelHandlerContext，释放和ChannelHandlerContext相关联的句柄等资源
		ctx.close();
	}

}
